﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using Mt.Site.Application.Common.Dto;
using Mt.Site.Application.WorkFlows.Dto.Reply;
using Mt.Site.Core.WorkFlows.Process.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Application.WorkFlows.Impl
{
    [AbpAuthorize]
    public class MyReplyMsgAppService: MtSiteAppServiceBase,IMyReplyMsgAppService
    {
        private readonly IRepository<CommonShortMsg, Guid> _commonShortMsgRepository;
        public MyReplyMsgAppService(IRepository<CommonShortMsg, Guid> commonShortMsgRepository)
        {
            _commonShortMsgRepository = commonShortMsgRepository;
        }
        public async Task<List<ReplyMsgItem>> GetReplyMsgList()
        {
            var userId = AbpSession.UserId;
            var query = from s in _commonShortMsgRepository.GetAll()
                        .Where(item => item.CreatorUserId == userId)
                        orderby s.CreationTime descending
                        select new ReplyMsgItem
                        {
                            Id = s.Id,
                            ReplyMsg = s.ReplyMsg
                        };
            var list = await query.ToListAsync();
            return list;
        }

        public async Task DeleteMyReplyMsg(EntityDto<Guid> input)
        {
            await _commonShortMsgRepository.DeleteAsync(input.Id);
        }


        public async Task AddMyReplyMsg(MyShortMsgInput input)
        {
            var userId = AbpSession.UserId;
            var e = await _commonShortMsgRepository.FirstOrDefaultAsync(item => item.ReplyMsg == input.ReplyMsg && item.CreatorUserId == userId);
            if (e == null)
            {
                await _commonShortMsgRepository.InsertAsync(new CommonShortMsg { ReplyMsg = input.ReplyMsg});
            }
            else
            {
                throw new UserFriendlyException("当前常用语已添加!");
            }
        }
    }
}
